package com.wswy.wzcx.model

import android.graphics.Paint
import android.os.Build
import android.support.v4.content.ContextCompat
import android.text.*
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.widget.TextView
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.model.resp.QueryResult
import com.wswy.wzcx.model.resp.TrafficViolationResp
import com.wswy.wzcx.model.topic.CommentModel
import com.wswy.wzcx.model.topic.TopicModel
import com.wswy.wzcx.ui.main.community.CommentVO
import com.wswy.wzcx.ui.main.community.CommunityViewHolders
import com.wswy.wzcx.ui.main.community.TopicVO
import com.wswy.wzcx.utils.StringUtils

object Converter {

    private const val TAG = "Converter"

    fun userCar2CarModel(userCarInfo: UserCarInfo):CarInfoModel{
        return CarInfoModel().apply {
            carId = "${userCarInfo.id}"
            carNo = userCarInfo.carNo
            engineNo = userCarInfo.engineNo
            frameNo = userCarInfo.frameNo
            carType = userCarInfo.carType

            userCarInfo.carExtendInfo?.carTypeData?.series?.let {
                seriesId = it.id
                series = it.name
            }
            userCarInfo.carExtendInfo?.carTypeData?.model?.let {
                specificationId = it.id
                model = it.name
            }

        }
    }


    fun convert2Result(resp: TrafficViolationResp): QueryResult {
        val result = QueryResult()

        result.userCarInfo = resp.userCarInfo
        result.fromCache = resp.fromCache
        result.noCache = resp.noCache
        resp.fineData?.run {

            if (hasError()){
                result.errorCode = code?:0
                result.errorMsg = errMsg
            }else{
                result.showTips = fineData?.showFineTips?:false

                result.fineList = getFineList()
            }
        }

        return result
    }


    private val maxW = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(50f)


    private val vPaint = TextView(AppContext.getContext()).apply {
        textSize = 15f
    }.paint

    private val placeW = vPaint.measureText("...全文")


    fun convert2TopicVO(model: TopicModel,needPreview:Boolean = false,imagePreview:Boolean = true):TopicVO{
        val len = model.images?.size?:0

        var type = CommunityViewHolders.TYPE_TOPIC_1

        val preview = if (!needPreview) model.content else model.content?.let {


            val layout =if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                StaticLayout.Builder.obtain(it,0,it.length, vPaint, maxW)
                        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                        .setLineSpacing(0.0f,1.0f)
                        .setIncludePad(false)
                        .build()
            } else {
                StaticLayout(it,vPaint,maxW, Layout.Alignment.ALIGN_NORMAL,
                        1.0f,0.0f,false)

            }

            val count = layout.getLineCount()
            val ret = SpannableStringBuilder()
            if (count > 4) {
                ret.append(it.subSequence(0,layout.getLineEnd(4)))

                val lastLine = it.substring(layout.getLineStart(4),layout.getLineEnd(4))

                val tmpLength = ret.length
                if (vPaint.measureText(lastLine) + placeW > maxW){

                    var lastOffset = 2
                    var lastTmp = ret.subSequence(tmpLength - lastOffset, tmpLength)
                    while (vPaint.measureText(lastTmp, 0, lastTmp.length) < placeW) {
                        lastOffset++
                        lastTmp = ret.subSequence(tmpLength - lastOffset, tmpLength)
                    }
                    //删除多余文字
                    ret.delete(tmpLength - lastOffset, tmpLength)
                }else{
                    //删除换行
                    ret.delete(tmpLength-1,tmpLength)
                }

                ret.append("...")
                ret.append(SpannableString("全文").apply {
                    setSpan(ForegroundColorSpan(ContextCompat.getColor(AppContext.getContext(), R.color.colorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                })

                ret
            } else {
                it
            }
        }

        if (len >0){
            type = CommunityViewHolders.BASE_IMG_TYPE + len
        }

        val imageSuffix= if (!imagePreview) null else  when(type){
            CommunityViewHolders.TYPE_TOPIC_IMG_1 -> {
                "?x-oss-process=image/resize,w_400"
            }
            in CommunityViewHolders.TYPE_TOPIC_IMG_2..CommunityViewHolders.TYPE_TOPIC_IMG_9 -> {
                "?x-oss-process=image/resize,w_200"
            }
            else -> null
        }

        return TopicVO(type,
                model,
                StringUtils.formatTime(model.createTime*1000),
                model.statNumber,
                model.commentNumber,
                model.whetherStar,
                preview,
                imageSuffix,
                needPreview
        )
    }


    fun convert2CommentVO(model: CommentModel):CommentVO{
        return CommentVO(model,
                //DateFormat.format("MM-dd HH:mm",model.createTime*1000),
                StringUtils.formatTime(model.createTime*1000),
                model.statNumber,
                model.whetherStar)
    }

}